package app.project.directionlensproject.fragment;

import java.lang.reflect.Array;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.google.android.gms.internal.n;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import app.project.directionlensproject.ListPlaceActivity;
import app.project.directionlensproject.MyApplication;
import app.project.directionlensproject.R;
import app.project.directionlensproject.adapter.ItemListPlaceAdapter;
import app.project.directionlensproject.map.MapActivity;
import app.project.directionlensproject.map.PlaceAddActivity;
import app.project.directionlensproject.map.PlaceDetailActivity;
import app.project.directionlensproject.map.PlaceEditActivity;
import app.project.directionlensproject.model.Place;
import app.project.directionlensproject.serverapi.ServerAPI;
import app.project.directionlensproject.util.AsyncTask;
import app.project.directionlensproject.util.BundleKeys;
import app.project.directionlensproject.util.CommonUtils;
import app.project.directionlensproject.util.Constants;
import app.project.directionlensproject.util.CustomHttpClient;
import app.project.directionlensproject.util.DialogUtils;
import app.project.directionlensproject.util.GetDataTask;
import app.project.directionlensproject.util.IGetDataTask;
import app.project.directionlensproject.util.Utilities;

public class FgListPlace extends ListFragment {
	public static int TYPE_SYTEM = 1;
	public static int TYPE_UNAPPROVE = 2;
	public static int TYPE_APPROVE = 3;
	public static int TYPE_FAVORITE = 4;
	public static final int TYPE_GOOGLE_SEARCH = 5;

	public ArrayList<Place> arrPlaces;
	public boolean isInitPlace = false;
	public ItemListPlaceAdapter adapter;

	private int categoryID, typePlace;
	private double locationx, locationy;
	private String searchStr;
	private String emptyText = null;
	public static ArrayList<Place> listCachePlace; // cache list sytem palce
	public static ArrayList<Place> listPlaceGoogle;
	
	Bundle bundle;
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (emptyText != null)
			setEmptyText(emptyText);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initData();

		getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int position, long arg3) {
				DialogInterface.OnClickListener menuContextClick = new OnClickListener() {
					public void onClick(DialogInterface arg0, int witch) {
						Place p = arrPlaces.get(position);
						if (typePlace == TYPE_SYTEM
								|| typePlace == TYPE_APPROVE) {
							addPlaceToFavorite(p, true);
						} else if (typePlace == TYPE_FAVORITE) {
							removePlaceFromFavorite(p);
						} else if (typePlace == TYPE_GOOGLE_SEARCH) {
							addPlace(p);
						} else {
							if (witch == 0)
								removeUserPlace(p);
							else if (witch == 1) {
								editPlace(p);
							} else
								addPlaceToFavorite(p, false);
						}
					}
				};
				DialogUtils.showPlaceMenuContext(getActivity(), typePlace,
						menuContextClick);
				return true;
			}
		});

		getListView().setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				detailPlace(arrPlaces.get(position));
			}
		});
	}

	private void addPlace(final Place p) {
		// go to add place
		Intent it = new Intent(getActivity(), PlaceAddActivity.class);
		it.putExtra("place", p);
		it.putExtra(BundleKeys.IS_GOOGLE, true);
		it.putExtra(BundleKeys.CATE_ID, categoryID);
		startActivity(it);
	}

	private void editPlace(final Place p) {
		Intent it = new Intent(getActivity(), PlaceEditActivity.class);
		it.putExtra("place", p);
		startActivity(it);
	}

	private void detailPlace(final Place p) {
		Intent it = new Intent(getActivity(), PlaceDetailActivity.class);
		it.putExtra("place", p);
		it.putExtra(BundleKeys.CATE_ID, categoryID);
		startActivity(it);
	}

	private void removePlaceFromFavorite(final Place p) {
		final String tokenid = CommonUtils.getStringSetting(getActivity(),
				Constants.TOKEN_ID, null);
		new GetDataTask(getActivity(), new IGetDataTask() {
			public void onPostExecute(boolean result) throws Exception {
				if (result) {
					Toast.makeText(getActivity(),
							R.string.delete_from_favorite_sucess,
							Toast.LENGTH_LONG).show();
					arrPlaces.remove(p);
					adapter.notifyDataSetChanged();
				} else
					Toast.makeText(getActivity(),
							R.string.delete_from_favorite_error,
							Toast.LENGTH_LONG).show();
			};

			@Override
			public boolean doInBackGround() throws Exception {
				return ServerAPI.RemoveUserFavouritePlaces(tokenid, p.uniqueid);
			}
		}, true).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void addPlaceToFavorite(final Place p, final boolean isSystemPlace) {
		final String tokenid = CommonUtils.getStringSetting(getActivity(),
				Constants.TOKEN_ID, null);
		new GetDataTask(getActivity(), new IGetDataTask() {
			public void onPostExecute(boolean result) throws Exception {
				if (result) {
					Toast.makeText(getActivity(),
							R.string.add_to_favorite_sucess, Toast.LENGTH_LONG)
							.show();
					FgListPlace FgFavorite = ((ListPlaceActivity) getActivity()).FgFavorite;
					if (FgFavorite != null) {
						FgFavorite.arrPlaces.add(p);
						FgFavorite.adapter.notifyDataSetChanged();
					}
				} else
					Toast.makeText(getActivity(),
							R.string.add_to_favorite_error, Toast.LENGTH_LONG)
							.show();
			};

			@Override
			public boolean doInBackGround() throws Exception {
				if (isSystemPlace)
					return ServerAPI.SetSystemFavouritePlaces(tokenid,
							p.uniqueid);
				else
					return ServerAPI
							.SetUserFavouritePlaces(tokenid, p.uniqueid);
			}
		}, false).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void removeUserPlace(final Place p) {
		final String tokenid = CommonUtils.getStringSetting(getActivity(),
				Constants.TOKEN_ID, null);
		new GetDataTask(getActivity(), new IGetDataTask() {
			public void onPostExecute(boolean result) throws Exception {
				if (result) {
					Toast.makeText(getActivity(), R.string.delete_place_sucess,
							Toast.LENGTH_LONG).show();
					arrPlaces.remove(p);
					adapter.notifyDataSetChanged();
				} else
					Toast.makeText(getActivity(), R.string.delete_place_error,
							Toast.LENGTH_LONG).show();
			};

			@Override
			public boolean doInBackGround() throws Exception {
				return ServerAPI.RemoveUserPlaces(tokenid, p.uniqueid);
			}
		}, true).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private String getCateGoogleName(int cateID) {
		if (cateID == 1)
			return null;
		else if (cateID == 2)
			return "restaurant%7Cfood%7Cbakery%7Ccafe";
		else if (cateID == 3)
			return "shopping_mall%7Cstore%7Cbicycle_store%7Cbook_store%7Cclothing_store%7Cconvenience_store%7Cdepartment_store%7Celectronics_store%7Cfurniture_store%7Chardware_store%7Chome_goods_store%7Cjewelry_store%7Cliquor_store%7Cpet_store%7Cshoe_store%7Cflorist";
		else if (cateID == 4)
			return "bank%7Catm%7Caccounting%7Cfinance";
		else if (cateID == 5)
			return "fire_station%7Cpolice%7Cdoctor%7Cdentist";
		else if (cateID == 6)
			return "gas_station";
		else if (cateID == 7)
			return "movie_theater%7Ccasino%7Cmovie_rental%7Cmuseum%7Cnight_club%7Czoo%7Cstadium%7Crv_park";
		else if (cateID == 8) {
			return "lodging";
		} else if (cateID == 9)
			return "airport%7Ctrain_station%7Cbus_station%7Ctaxi_stand%7Ctravel_agency";
		else if (cateID == 10)
			return "university";
		else
			return null;
	}

	private void initData() {
		bundle = getArguments();
		if (bundle != null) {
			categoryID = bundle.getInt(BundleKeys.CATE_ID, -1);
			typePlace = bundle.getInt(BundleKeys.TYPE_PLACE, 1);
			locationx = bundle.getDouble(BundleKeys.LOCATION_X, 0);
			locationy = bundle.getDouble(BundleKeys.LOCATION_Y, 0);
			searchStr = bundle.getString(BundleKeys.SEARCH_STR);
			if (bundle.getBoolean(BundleKeys.IS_GOOGLE)) {
				if (searchStr != null) {
					new GetDataTask(getActivity(), new IGetDataTask() {

						String api1 = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=";
						String api2 = "&sensor=true&key=AIzaSyA20wem8Emwk7i-xKKxMtltJ_SENweYpqM";

						// CommonUtils.saveBooleanSetting(MyApplication.getAppContext(),
						// Constants.IS_SEARCH_ALL, isChecked);
						@Override
						public void onPostExecute(boolean result)
								throws Exception {
							super.onPostExecute(result);
							isInitPlace = true;
							try {
								if (arrPlaces == null) {
									arrPlaces = new ArrayList<Place>();
									setEmptyText(getString(R.string.empty_by_error));
								} else {
									setEmptyText(getString(R.string.empty_place));
								}
							} catch (Exception e) {
							}

							adapter = new ItemListPlaceAdapter(getActivity(),
									arrPlaces, locationx, locationy);
							setListAdapter(adapter);
						}

						@Override
						public boolean doInBackGround() throws Exception {
							searchStr = searchStr.replace(' ', '+');
							String api = "";
							if (!CommonUtils.getBooleanSetting(
									MyApplication.getAppContext(),
									Constants.IS_SEARCH_ALL, false)) {
								int radius = CommonUtils.getIntSetting(
										MyApplication.getAppContext(),
										Constants.RADIUS, 5);
								api = api1 + searchStr + api2 + "&radius="
										+ radius + "&location=" + locationx
										+ "," + locationy;
							} else {
								api = api1 + searchStr + api2;
							}

							Log.e("APISearch", api);
							String response = CustomHttpClient
									.executeHttpGet(api);
							arrPlaces = initGooglePlace(response);
							if (!CommonUtils.getBooleanSetting(
									MyApplication.getAppContext(),
									Constants.IS_SEARCH_ALL, false)) {
								ArrayList<Place> arrPlaces1 = new ArrayList<Place>();
								int radius = CommonUtils.getIntSetting(
										MyApplication.getAppContext(),
										Constants.RADIUS, 5);
								for (int i = 0; i < arrPlaces.size(); i++) {
									if (arrPlaces.get(i).getDistance() <= (float) radius) {
										arrPlaces1.add(arrPlaces.get(i));
									}
								}
								arrPlaces=arrPlaces1;
							}

							ListPlaceActivity.listCurrentPlace = arrPlaces;
							listPlaceGoogle=arrPlaces;
							return false;
						}
					}, false).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
					return;
				} else {
					
					String googleCate = getCateGoogleName(categoryID);
					int radius = CommonUtils.getIntSetting(
							MyApplication.getAppContext(), Constants.RADIUS, 5);
					radius = radius * 1000;
					String api1 = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=";
					String api1_1 = "&radius=" + radius;
					String api2 = "";
					if (googleCate != null)
						api2 = "&types=" + googleCate;
					String api3 = "&sensor=false&key=AIzaSyA20wem8Emwk7i-xKKxMtltJ_SENweYpqM";
					final String api = api1 + locationx + "," + locationy
							+ api1_1 + api2 + api3;
					Log.e("APINearBy", api);
					// Log.e("ItemIndex121",api.charAt(121)+"");
					// Log.e("ItemIndex122",api.charAt(122)+"");
					// Log.e("ItemIndex123",api.charAt(123)+"");
					new GetDataTask(getActivity(), new IGetDataTask() {
						@Override
						public void onPostExecute(boolean result)
								throws Exception {
							super.onPostExecute(result);
							isInitPlace = true;
							try {
								if (arrPlaces == null) {
									arrPlaces = new ArrayList<Place>();
									setEmptyText(getString(R.string.empty_by_error));
								} else {
									setEmptyText(getString(R.string.empty_place));
								}
							} catch (Exception e) {
							}

							adapter = new ItemListPlaceAdapter(getActivity(),
									arrPlaces, locationx, locationy);
							setListAdapter(adapter);
						}

						@Override
						public boolean doInBackGround() throws Exception {
							String response = CustomHttpClient
									.executeHttpGet(api);
							Log.e("ResponseGoogle", response);
							arrPlaces = initGooglePlace(response);
							ListPlaceActivity.listCurrentPlace = arrPlaces;
							listPlaceGoogle=arrPlaces;
							return false;
						}
					}, false).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
					return;
				}
			}
			updateData(false);
		}
		
	}

	private ArrayList<Place> initGooglePlace(String jsonReponse)
			throws Exception {
		ArrayList<Place> result = new ArrayList<Place>();
		JSONObject jsonObject = new JSONObject(jsonReponse);
		JSONArray resultsArray = jsonObject.getJSONArray("results");
		int length = resultsArray.length();
		for (int i = 0; i < length; i++) {
			JSONObject tmpObject = resultsArray.getJSONObject(i);
			JSONObject geometryObject = tmpObject.getJSONObject("geometry");
			JSONObject locationObject = geometryObject
					.getJSONObject("location");
			Place p = new Place();
			p.locationx = (float) locationObject.getDouble("lat");
			p.locationy = (float) locationObject.getDouble("lng");
			p.placename = tmpObject.getString("name");
			if (tmpObject.has("formatted_address"))
				p.description = tmpObject.getString("formatted_address");
			else
				p.description = "";
			p.image = Utilities.getInstance().getStringBase64FromImageUrl(
					tmpObject.getString("icon"));
			// p.categoryid=Integer.parseInt(getCateGoogleName(categoryID));
			// //ADD T
			result.add(p);
		}
		return result;
	}

	@Override
	public void setEmptyText(CharSequence text) {
		try {
			emptyText = text.toString();
			super.setEmptyText(text);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void updateData(boolean isShowProgress) {
		isInitPlace = false;
		final int radius = CommonUtils.getIntSetting(
				MyApplication.getAppContext(), Constants.RADIUS, 5);
		final boolean isGetAll = CommonUtils.getBooleanSetting(
				MyApplication.getAppContext(), Constants.IS_DISPLAY_ALL, false);
		new GetDataTask(getActivity(), new IGetDataTask() {
			@Override
			public void onPostExecute(boolean result) throws Exception {
				super.onPostExecute(result);
				isInitPlace = true;
				try {
					if (arrPlaces == null) {
						arrPlaces = new ArrayList<Place>();
						setEmptyText(getString(R.string.empty_by_error));

					} else {
						setEmptyText(getString(R.string.empty_place));
					}
				} catch (Exception e) {
				}

				adapter = new ItemListPlaceAdapter(getActivity(), arrPlaces,
						locationx, locationy);
				setListAdapter(adapter);

				if (typePlace == TYPE_SYTEM || searchStr != null
						|| typePlace == TYPE_UNAPPROVE) {
					listCachePlace = arrPlaces;
					ListPlaceActivity.listCurrentPlace = arrPlaces;
				}
			}

			@Override
			public boolean doInBackGround() throws Exception {
				String tokenid = CommonUtils.getStringSetting(
						MyApplication.getAppContext(), Constants.TOKEN_ID, null);
				
				if (searchStr != null) {
					if(CommonUtils.getBooleanSetting(
						MyApplication.getAppContext(),
						Constants.IS_SEARCH_ALL, false)){
						arrPlaces=ServerAPI.SearchAllPlace(tokenid, searchStr, 0, 100);
					}else{
						arrPlaces = ServerAPI.SearchPlace(tokenid, searchStr,
								locationx, locationy, radius, 0, 100);
					}
					
					return false;
				}
				if (typePlace == TYPE_SYTEM) {
					if (listCachePlace != null) {						
						if(bundle.getBoolean(BundleKeys.IS_GOOGLE))
						{
							arrPlaces=listPlaceGoogle;
						}else{
							arrPlaces = listCachePlace;
						}
						
						ListPlaceActivity.listCurrentPlace = arrPlaces;
						Log.d("aa", "return");
						return false;
					}
					Log.d("aa", "not has");
					arrPlaces = ServerAPI.GetNearbyPlace(categoryID, locationx,
							locationy, radius, 0, 100);
					ListPlaceActivity.listCurrentPlace = arrPlaces;
					listCachePlace = arrPlaces;
					Log.d("aa", "save");
				} else if (typePlace == TYPE_UNAPPROVE) {
					if (!isGetAll)
						arrPlaces = ServerAPI.GetPlaceUnapproved(tokenid,
								locationx, locationy, radius, 0, 100);
					else
						arrPlaces = ServerAPI.GetAllPlaceUnapproved(tokenid, 0,
								100);
					ListPlaceActivity.listCurrentPlace = arrPlaces;
				} else if (typePlace == TYPE_APPROVE) {
					if (isGetAll)
						arrPlaces = ServerAPI.GetAllPlaceApproved(tokenid, 0,
								100);
					else
						arrPlaces = ServerAPI.GetPlaceApproved(tokenid,
								locationx, locationy, radius, 0, 100);
					ListPlaceActivity.listCurrentPlace = arrPlaces;
				} else if (typePlace == TYPE_FAVORITE) {
					ArrayList<Place> list1, list2;
					if (isGetAll) {
						Log.e("IsGetall", "true");
						list1 = ServerAPI.GetAllUserFavouritePlaces(tokenid, 0,
								100);
						list2 = ServerAPI.GetAllSystemFavouritePlaces(tokenid,
								0, 100);
					} else {
						Log.e("IsGetall", "false");
						list1 = ServerAPI.GetUserFavouritePlaces(tokenid,
								locationx, locationy, radius, 0, 100);
						list2 = ServerAPI.GetSystemFavouritePlaces(tokenid,
								locationx, locationy, radius, 0, 100);
					}
					arrPlaces = new ArrayList<Place>();
					if (list1 != null) {
						Log.e("SizeList1", list1.size() + "");
						arrPlaces.addAll(list1);
					}

					if (list2 != null) {
						Log.e("SizeList2", list2.size() + "");
						arrPlaces.addAll(list2);
					}

					ListPlaceActivity.listCurrentPlace = arrPlaces;
				}
				return false;
			}
		}, isShowProgress).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	public void updateRotate(float corner) {
		try {
			if (arrPlaces == null)
				return;
			else {
				for (Place place : arrPlaces) {
					place.setCorner(corner);
				}
				adapter.notifyDataSetChanged();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

	}

}
